const sql = require('mssql');
const { conStr } = require("../config");

const getTableList = async (tableName) => {
  const con = await sql.connect(conStr).catch(err => {
    console.log("错误", err);
  });
  if (con == undefined) {
    return null
  }
  const sqlstr = `
  SELECT TOP 1000 *
  FROM [${tableName}]
  `
  const result = (await sql.query(sqlstr)).recordset;
  con.close();
  return result;
}

const rule = {
  "varchar": {
    type: "string",
    query(name) {
      return `&& (req.${name} == null ? 1 == 1 : u.${name}.Contains(req.${name}))`
    },
    column(item, idKey, projectName, method) {
      if (item.stringType == "img") {
        return `{
        title: '${item.description ? item.description : item.name}',
        dataIndex: '${item.name}',
        valueType: "text",
        hideInSearch: true,
        hideInTable: true,
        rules: [{
          required: ${item.required},
        }],
        renderFormItem: (item, { defaultRender, ...rest }, form) => {
          return (<ImageBox arr={[]} maxSize={3} action="/api/${projectName}/uploadImg" />)
        },
      },
      `
      }
      if (item.stringType == "richText") {
        return `{
          title: '${item.description ? item.description : item.name}',
          dataIndex: '${item.name}',
          valueType: "textarea",
          hideInSearch: ${!item.isSearch},
          hideInTable: ${!item.isTable},
          hideInForm: ${!item.isForm},
          rules: [{
            required: ${item.required},
          }],
          ${item.enum.length == 0 ? "" : `valueEnum: {
            ${item.enum.map(eitem => `
            "${eitem.key}": {
              text: '${eitem.value}',
            },
            `).join('')}
          },`}
        },
        `
      }
      return `{
        title: '${item.description ? item.description : item.name}',
        dataIndex: '${item.name}',
        valueType: "text",
        hideInSearch: ${!item.isSearch},
        hideInTable: ${!item.isTable},
        hideInForm: ${!item.isForm},
        rules: [{
          required: ${item.required},
        }],
        ${item.enum.length == 0 ? "" : `valueEnum: {
          ${item.enum.map(eitem => `
          "${eitem.key}": {
            text: '${eitem.value}',
          },
          `).join('')}
        },`}
      },
      `
    },
    async mock(item) {
      if (item.stringType == "img") {
        return { [`${item.name}|1`]: '@image("300x300","@color")' }
      }
      if (item.enum.length != 0) {
        return { [`${item.name}|1`]: item.enum.map(mitem => mitem.key) }
      }
      else {
        return item.name.toLowerCase().includes("name") ?
          { [`${item.name}|1`]: "@cname" } :
          { [`${item.name}|1`]: "@cword(3,10)" };
      }
    },
    insertSql(val){
      return `'${val}'`
    },
  },
  "int": {
    type: "Nullable<int>",
    query(name) {
      return `&& (req.${name} == null ? 1 == 1 : u.${name} == req.${name})`
    },
    column(item) {
      return item.fk ? `
      {
        title: '${item.fk.cName}',
        dataIndex: '${item.name}',
        hideInTable: true,
        hideInSearch: true,
        renderFormItem: (item, { defaultRender, ...rest }, form) => {
          return (<Select showSearch options={this.state.f${item.fk.displayName}Options} filterOption={(input, option) => option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0} />)
        },
        rules: [{
          required: ${item.required},
        }],
      },
      {
        title: '${item.fk.cName}',
        dataIndex: 'f${item.fk.displayName}',
        valueType: "text",
        hideInSearch: ${!item.isSearch},
        hideInTable: ${!item.isTable},
        hideInForm: true,
      },
      `: `
      {
        title: '${item.description ? item.description : item.name}',
        dataIndex: '${item.name}',
        ${item.enum.length == 0 ? `valueType: "digit",` : ''}
        hideInSearch: ${!item.isSearch},
        hideInTable: ${!item.isTable},
        hideInForm: ${!item.isForm},
        rules: [{
          required: ${item.required},
        }],
        ${item.enum.length == 0 ? `formItemProps: { precision: 0, max: 999999, maxLength:6 },` : ''}
        ${item.enum.length == 0 ? "" : `valueEnum: {
          ${item.enum.map(eitem => `"${eitem.key}": {
            text: '${eitem.value}',
          },
          `).join('')}
        },`}
      },
      `;
    },
    async mock(item) {
      if (item.fk) {
        //外键
        const ids = (await getTableList(item.fk.tableName)).map(mitem => mitem[item.fk.pkName]);
        return { [`${item.name}|1`]: ids }
      }
      else {
        if (item.enum.length != 0) {
          return { [`${item.name}|1`]: item.enum.map(mitem => Number(mitem.key)) }
        }
        else {
          return { [`${item.name}|1-9999`]: 1, }
        }
      }
    },
    insertSql(val){
      return `${val}`
    },
  },
  "decimal": {
    type: "Nullable<decimal>",
    query(name) {
      return `&& (req.${name} == null ? 1 == 1 : u.${name} == req.${name})`
    },
    column(item) {
      return `
      {
        title: '${item.description ? item.description : item.name}',
        dataIndex: '${item.name}',
        ${item.enum.length == 0 ? `valueType: "digit",` : ''}
        hideInSearch: ${!item.isSearch},
        hideInTable: ${!item.isTable},
        hideInForm: ${!item.isForm},
        rules: [{
          required: ${item.required},
        }],
        formItemProps: { precision: ${item.scale},  maxLength: 16 },
      },
      `;
    },
    async mock(item) {
      return { [`${item.name}|1-1000.${item.scale}`]: 1 }
    },
    insertSql(val){
      return `${val}`
    },
  },
  "bit": {
    type: "Nullable<bool>",
    query(name) {
      return `&& (req.${name} == null ? 1 == 1 : u.${name} == req.${name})`
    },
    column(item, idKey, projectName, method) {
      return !item.isSwitch ?
        `{
        title: '${item.description ? item.description : item.name}',
        dataIndex: '${item.name}',
        hideInSearch: ${!item.isSearch},
        hideInTable: ${!item.isTable},
        hideInForm: ${!item.isForm},
        rules: [{
          required: ${item.required},
        }],
        valueEnum: {
          [false]: {
            text: '禁用',
            status: 'Default',
          },
          [true]: {
            text: '启用',
            status: 'Processing',
          },
        },
      },
                `
        :
        `{
        title: '${item.description ? item.description : item.name}',
        dataIndex: '${item.name}',
        hideInSearch: ${!item.isSearch},
        hideInTable: ${!method.some(item => item == "Edit") ? "false" : "true"},
        hideInForm: ${!item.isForm},
        rules: [{
          required: ${item.required},
        }],
        valueEnum: {
          [false]: {
            text: '禁用',
            status: 'Default',
          },
          [true]: {
            text: '启用',
            status: 'Processing',
          },
        },
      },
      ${!method.some(item => item == "Edit") ? "" : `
      {
        title: '${item.description ? item.description : item.name}',
        dataIndex: '${item.name}1',
        valueType: 'option',
        render: (_, row) => {
          return (<Switch disabled={this.state.Switch${item.name}}
            checkedChildren={"可用"} unCheckedChildren={"禁用"}
            onChange={async (val) => {
              const success = await this.handleDeal({
                type: "操作",
                fields: {
                  ["${idKey}"]: row["${idKey}"],
                  ["${item.name}"]: val,
                },
                serviceMethod: ${projectName}Edit,
              });
              if (!success) {
                return;
              }
              if (!actionRef.current) {
                return;
              }
              actionRef.current.reload();
            }}
            checked={row["${item.name}"]}
          // defaultChecked={_}
          />)
        }
      },
      `}
                `
    },
    async mock(item) {
      return { [`${item.name}|1`]: [0, 1] }
    },
    insertSql(val){
      return `${val}`
    },
  },
  "datetime": {
    type: "string",
    query(name) {
      return `&& (req.${name} == null ? 1 == 1 : (u.${name} >= b_${name} && u.${name} <= e_${name}))`
    },
    column(item) {
      return !item.isSearch ?
        `
      {
        title: '${item.description ? item.description : item.name}',
        dataIndex: '${item.name}',
        valueType: "date",
        render: (_, row) => row["${item.name}"]? moment(row["${item.name}"]).format("YYYY-MM-DD HH:mm") : "",
        hideInSearch: true,
        hideInTable: ${!item.isTable},
        hideInForm: ${!item.isForm},
        rules: [{
          required: ${item.required},
        }],
      },
                `
        :
        `
      {
        title: '${item.description ? item.description : item.name}',
        dataIndex: '${item.name}',
        valueType: "date",
        render: (_, row) => row["${item.name}"]? moment(row["${item.name}"]).format("YYYY-MM-DD HH:mm") : "",
        hideInSearch: true,
        hideInTable: ${!item.isTable},
        hideInForm: ${!item.isForm},
        rules: [{
          required: ${item.required},
        }],
      },
      {
        title: '${item.description ? item.description : item.name}',
        dataIndex: '${item.name}',
        valueType: 'dateRange',
        hideInSearch: false,
        hideInTable: true,
        hideInForm: true,
      },
                `;

    },
    async mock(item) {
      return { [`${item.name}|1`]: "@datetime" }
    },
    insertSql(val){
      return `'${val}'`
    },
  },
}
module.exports = rule;